from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session
from info.utils.common import user_login_data
from info import constants
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blu
from flask import render_template

@index_blu.route('/')   # 根路由
@user_login_data
def index():
    current_app.logger.debug('debug')
    current_app.logger.error('error')
    # 获取当前登陆用户的id
    # user_id = session.get("user_id")
    # # 通过用户id获取用户信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger(e)
    user = g.user  # 通过g变量接收登陆用户的id参数

    # 新闻前台 点击排行
    # news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger(e)

    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())


    # 获取新闻分类数据
    categories = Category.query.all()
    categories_dicts = []
    for category in categories:
        categories_dicts.append(category.to_dict())

    data = {
        "user":user.to_dict() if user else None,
        "click_news_list":click_news_list,
        "categories":categories_dicts,
    }

    return render_template('news/index.html', data = data)    # 默认加载templates中的静态模板

@index_blu.route('/favicon.ico')     # 网页图标路由
def favicon():

    return current_app.send_static_file('news/favicon.ico')

# 新闻列表
@index_blu.route('/news_list')
def get_newslist():
    # 1 获取参数
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 20)
    cid = request.args.get('cid', '1')

    # 2 校验参数
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:

        page = 1
        per_page = 20


    # 3 查询数据进行分页
    # category_id=1时，新闻列表中没有数据，最新是按照新闻的时间进行展示的而不是cid
    # 3. 查询数据并分页
    # filters = [News.status == 0]

    filter=[]
    if cid != '1':
        filter.append(News.category_id==cid)
    try:
        # *filter是进行遍历，拆包
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page=page, per_page=per_page)
        # 获取所有的当前分页数据
        news = paginate.items
        # 总页数
        total_page = paginate.pages
        # 当前页数
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='查询数据错误')
    # 4 返回数据
    newslist = []
    for item in news:
        newslist.append(item.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg='ok',
                   newslist=newslist,
                   current_page=current_page,
                   cid=cid,
                   total_page=total_page)
























